import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:mall/constants.dart';
import 'package:mall/core/services/auth.dart';
import 'package:mall/core/providers/pages/mine/reg_new_model.dart';
import 'package:mall/core/providers/pages/mine/reg_new_qr_model.dart';
import 'package:mall/core/providers/pages/mine/req_code_model.dart';
import 'package:mall/core/providers/view_model.dart';
import 'package:mall/screens/mine/qrcode_page.dart';
import 'package:mall/screens/mine/webview_page.dart';
import 'package:mall/components/count_down_text.dart';
import 'package:provider/provider.dart';

import '../../theme.dart';

class RegisterPage extends StatefulWidget {
  static const routeName = '/RegisterPage';

  @override
  _RegisterPageState createState() => _RegisterPageState();
}

class _RegisterPageState extends State<RegisterPage> {
  final _inviteCodeController = TextEditingController();
  bool _checkProtocol = true;

  @override
  void dispose() {
    super.dispose();
    _inviteCodeController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(
          create: (context) => RegNewModel(context.read<Auth>()),
        ),
        ChangeNotifierProvider(
          create: (context) => RegNewQrModel(context.read<Auth>()),
        )
      ],
      child: Theme(
        data: darkTheme(),
        child: Scaffold(
          appBar: AppBar(),
          body: SingleChildScrollView(
            padding: EdgeInsets.symmetric(horizontal: 16),
            child: Builder(
              builder: (context) {
                RegNewModel model = Provider.of(context, listen: false);
                return Column(
                  children: <Widget>[
                    SizedBox(height: 50),
                    Text(
                      '用户注册',
                      style: TextStyle(fontSize: 28),
                    ),
                    SizedBox(height: 40),
                    Row(
                      children: <Widget>[
                        Expanded(
                          child: _WrapContainer(
                            child: TextFormField(
                              controller: _inviteCodeController,
                              decoration: InputDecoration(
                                hintText: '邀请码',
                              ),
                              onChanged: (value) {
                                model.inviteCode = value;
                              },
                            ),
                          ),
                        ),
                        SizedBox(width: 1),
                        Container(
                          alignment: Alignment.center,
                          color: Colors.white10,
                          width: 118,
                          height: 50,
                          child: FlatButton(
                            onPressed: () {
                              _onQrcodeClicked(context);
                            },
                            child: Text('扫码输入'),
                          ),
                        ),
                      ],
                    ),
                    _CheckBoxWidget(),
                    _WrapContainer(
                      child: TextField(
                        decoration: InputDecoration(
                          hintText: '手机号',
                        ),
                        keyboardType: TextInputType.phone,
                        onChanged: (value) {
                          model.mobile = value;
                        },
                      ),
                    ),
                    SizedBox(height: 15),
                    Row(
                      children: <Widget>[
                        Expanded(
                          child: Container(
                            child: _WrapContainer(
                              child: TextField(
                                decoration: InputDecoration(
                                  hintText: '验证码',
                                ),
                                onChanged: (value) {
                                  model.checkCode = value;
                                },
                              ),
                            ),
                          ),
                        ),
                        SizedBox(width: 1),
                        Container(
                          alignment: Alignment.center,
                          color: Colors.white10,
                          width: 118,
                          height: 50,
                          child: ChangeNotifierProvider(
                            create: (context) => ReqCodeModel(
                              Provider.of(context, listen: false),
                            ),
                            child: Consumer<ReqCodeModel>(
                              builder: (context, model, child) {
                                switch (model.viewState) {
                                  case ViewState.busy:
                                    return FlatButton(
                                      onPressed: null,
                                      child: SizedBox(
                                        width: 14,
                                        height: 14,
                                        child: CircularProgressIndicator(),
                                      ),
                                    );
                                  case ViewState.success:
                                    return FlatButton(
                                      onPressed: null,
                                      child: CountDownText(
                                        function: () {
                                          model.viewState = ViewState.idle;
                                        },
                                        style: TextStyle(
                                          color: Colors.grey,
                                          fontSize: 16,
                                        ),
                                      ),
                                    );
                                  default:
                                    return FlatButton(
                                      onPressed: () {
                                        _onCodeClicked(context);
                                      },
                                      child: Text('发送验证码'),
                                    );
                                }
                              },
                            ),
                          ),
                        ),
                      ],
                    ),
                    Container(
                      margin: EdgeInsets.only(top: 40),
                      width: double.infinity,
                      child: Consumer<RegNewModel>(
                        builder: (context, model, child) {
                          switch (model.viewState) {
                            case ViewState.busy:
                              return OutlineButton(
                                onPressed: null,
                                borderSide: BorderSide(color: Colors.white),
                                child: CircularProgressIndicator(),
                              );
                            default:
                              return OutlineButton(
                                onPressed: () {
                                  _onRegNewClicked(context);
                                },
                                borderSide: BorderSide(color: Colors.white),
                                child: Text(
                                  '立即注册',
                                  style: TextStyle(fontSize: 18),
                                ),
                              );
                          }
                        },
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.only(top: 8),
                      width: double.infinity,
                      child: Consumer<RegNewQrModel>(
                        builder: (context, model, child) {
                          switch (model.viewState) {
                            case ViewState.busy:
                              return FlatButton(
                                onPressed: null,
                                child: SizedBox(
                                  width: 14,
                                  height: 14,
                                  child: CircularProgressIndicator(),
                                ),
                              );
                            default:
                              return OutlineButton.icon(
                                onPressed: () {
                                  _onQrcodeRegClicked(context);
                                },
                                icon: Icon(
                                  Icons.filter_center_focus,
                                ),
                                borderSide: BorderSide(
                                  color: Colors.white,
                                ),
                                label: Text(
                                  '扫码注册',
                                  style: TextStyle(fontSize: 18),
                                ),
                              );
                          }
                        },
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.only(
                        top: 40,
                        bottom: 40,
                      ),
                      child: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Checkbox(
                            value: _checkProtocol,
                            onChanged: (value) {
                              setState(() {
                                _checkProtocol = value;
                              });
                            },
                          ),
                          RichText(
                            text: TextSpan(
                              text: '已阅读且同意',
                              children: [
                                TextSpan(
                                  text: '《平台用户协议》',
                                  style: TextStyle(color: Colors.yellow),
                                  recognizer: TapGestureRecognizer()
                                    ..onTap = () {
                                      _onAgreementClicked(context);
                                    },
                                ),
                                TextSpan(text: '内容'),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                );
              },
            ),
          ),
        ),
      ),
    );
  }

  /// 扫码录入
  void _onQrcodeClicked(BuildContext context) async {
    // 导航扫码
    var result = await Navigator.of(context).pushNamed(QrcodePage.routeName);
    if (result == null) {
      return;
    }
    try {
      var uri = Uri.parse(result);
      var queryParameters = uri.queryParameters;
      var invitedCode = queryParameters['ic'];
      if (invitedCode == null) {
        throw '无效二维码';
      }
      RegNewModel model = Provider.of(context, listen: false);
      model.inviteCode = invitedCode;
      _inviteCodeController.text = invitedCode;
    } catch (e) {
      EasyLoading.showToast('无效二维码');
    }
  }

  /// 获取验证码
  void _onCodeClicked(BuildContext context) async {
    RegNewModel regNewModel = Provider.of(context, listen: false);
    var mobile = regNewModel.mobile;

    ReqCodeModel reqCodeModel = Provider.of(context, listen: false);
    var viewState = await reqCodeModel.reqCode(ReqCodeModel.USER_REGISTER, mobile);

    switch (viewState) {
      case ViewState.error:
        EasyLoading.showToast(reqCodeModel.errorMessage);
        break;
      default:
        EasyLoading.showToast('验证码已发送');
        break;
    }
  }

  /// 立即注册
  void _onRegNewClicked(BuildContext context) async {
    // 判断协议
    if (!_checkProtocol) {
      EasyLoading.showToast("请阅读协议");
      return;
    }
    // 注册
    RegNewModel model = Provider.of(context, listen: false);
    var viewState = await model.regNew();
    switch (viewState) {
      case ViewState.error:
        EasyLoading.showToast(model.errorMessage);
        break;
      default:
        await showDialog(
          context: context,
          builder: (context) {
            var data = model.data;
            return AlertDialog(
              content: Text(
                '用户名：${data.username}\n密码：${data.originPassword}',
              ),
              actions: <Widget>[
                FlatButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                  child: Text('确定'),
                ),
              ],
            );
          },
        );
        Navigator.of(context).pop(model.data);
        break;
    }
  }

  /// 扫码注册
  void _onQrcodeRegClicked(BuildContext context) async {
    // 判断协议
    if (!_checkProtocol) {
      EasyLoading.showToast("请阅读协议");
      return;
    }
    // 导航扫码
    var result = await Navigator.of(context).pushNamed(QrcodePage.routeName);
    if (result == null) {
      return;
    }
    try {
      var uri = Uri.parse(result);
      var queryParameters = uri.queryParameters;
      var encodedClientId = queryParameters['client_id'];
      var invitedCode = queryParameters['ic'];
      if (encodedClientId == null || invitedCode == null) {
        throw '无效二维码';
      }
      RegNewQrModel model = Provider.of(context, listen: false);
      var viewState = await model.regNewQr(encodedClientId, invitedCode);
      switch (viewState) {
        case ViewState.error:
          EasyLoading.showToast(model.errorMessage);
          break;
        default:
          var data = model.data;
          await showDialog(
            context: context,
            builder: (context) {
              return Theme(
                data: buildThemeData(context),
                child: AlertDialog(
                  title: Text("注册成功"),
                  content: Text(
                    '用户名：${data.username}\n密码：${data.originPassword}',
                  ),
                  actions: <Widget>[
                    FlatButton(
                      onPressed: () {
                        Navigator.of(context).pop();
                      },
                      child: Text('确定'),
                    ),
                  ],
                ),
              );
            },
          );
          // 返回登录页面
          Navigator.of(context).pop(data);
          break;
      }
    } catch (e) {
      debugPrint('e = $e');
      EasyLoading.showToast('无效二维码');
    }
  }

  /// 阅读协议
  void _onAgreementClicked(BuildContext context) {
    Navigator.of(context).pushNamed(
      WebViewPage.routeName,
      arguments: WebViewPageArgs(
        '用户协议',
        '请仔细阅读以下条款：',
        '$api_base_url/app/protocol/user',
      ),
    );
  }
}

/// 可选项
class _CheckBoxWidget extends StatefulWidget {
  @override
  __CheckBoxWidgetState createState() => __CheckBoxWidgetState();
}

class __CheckBoxWidgetState extends State<_CheckBoxWidget> {
  var _checkbox = false;

  @override
  Widget build(BuildContext context) {
    RegNewModel model = Provider.of(context, listen: false);
    return Column(
      children: <Widget>[
        Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Container(
              width: 14,
              height: 14,
              margin: EdgeInsets.only(
                left: 5,
                top: 15,
                bottom: 15,
                right: 10,
              ),
              child: Checkbox(
                  value: _checkbox,
                  onChanged: (value) {
                    model.clearOptional();
                    setState(() {
                      _checkbox = value;
                    });
                  }),
            ),
            Text('自定义账号'),
          ],
        ),
        if (_checkbox)
          Column(
            children: <Widget>[
              _WrapContainer(
                child: TextField(
                  decoration: InputDecoration(
                    hintText: '用户账号',
                  ),
                  onChanged: (value) {
                    model.username = value;
                  },
                ),
              ),
              _WrapContainer(
                margin: EdgeInsets.only(top: 6),
                child: TextField(
                  decoration: InputDecoration(
                    hintText: '用户密码',
                  ),
                  obscureText: true,
                  onChanged: (value) {
                    model.password = value;
                  },
                ),
              ),
              _WrapContainer(
                margin: EdgeInsets.only(
                  top: 6,
                  bottom: 15,
                ),
                child: TextField(
                  decoration: InputDecoration(
                    hintText: '确认密码',
                  ),
                  obscureText: true,
                  onChanged: (value) {
                    model.passwordConfirm = value;
                  },
                ),
              ),
            ],
          )
      ],
    );
  }
}

class _WrapContainer extends StatelessWidget {
  final EdgeInsetsGeometry margin;
  final Widget child;

  _WrapContainer({
    Key key,
    this.margin,
    this.child,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      alignment: Alignment.center,
      padding: EdgeInsets.symmetric(horizontal: 16),
      color: Colors.white10,
      height: 50,
      margin: margin,
      child: child,
    );
  }
}
